//
// Created by baigui on 2021/10/18.
//

#include "MkvDemux.h"
#include "common.h"

#include <stdio.h>
#include <FileDatasource.h>
#include <libavutil/intreadwrite.h>
#include <mkv/MKVNodeBase.h>

MkvDemux::~MkvDemux() {

}

MkvDemux::MkvDemux(weak_ptr<MediaPlayer> player) : Demux(player) {

}


bool MkvDemux::Open(void *path1) {

    char *psz_url = (char *) path1;
    uint8_t *p_peek;

    mFileDatasource = new FileDatasource(psz_url);
    uint64_t total = 0;
    int len_mask = 0x80, size = 1, n = 1, i;

    uint8_t b[64] = {0};
    uint8_t *buf = b;
    if (mFileDatasource->sp_stream_Peek(&buf, 64) != 64)
        return false;
    /* EBML header? */
    if (AV_RB32(buf) != EBML_ID_HEADER)
        return 0;

    /* length of header */
//    total = getLength(buf+4,8,&size);

    /* Does the probe data contain the whole header? */
//    if (buf_size < 4 + size + total)
//        return 0;

    /* The header should contain a known document type. For now,
     * we don't parse the whole header but simply check for the
     * availability of that array of characters inside the header.
     * Not fully fool-proof, but good enough. */
    HeaderNode *headerNode = new HeaderNode(mFileDatasource,0);

    headerNode->getBasicInfo();

    headerNode->process();

    mFileDatasource->sp_stream_Seek(headerNode->getNodeSize());
    contentNode = new ContentNode(mFileDatasource,headerNode->getNodeSize());
    contentNode->getBasicInfo();

    contentNode->process();

    return true;
}

bool MkvDemux::start() {

    return false;
}

void MkvDemux::requestbuffer() {

}

void MkvDemux::handle(int what, void *) {

}